import { connect, history } from 'umi';
import { Steps, Button, Space, message } from 'antd';
import React, { useContext, useEffect, useMemo, useState } from 'react';

import UpdateSourceInviteView from './UpdateSourceInvite';
import UpdateSourceClarifyView from './UpdateSourceClarify';
import UpdateSourceExpertsView from './UpdateSourceExperts';
import UpdateSourceSupplierView from './UpdateSourceSupplier';
import UpdateSourceCalibrateView from './UpdateSourceCalibrate';

import '../common/style.less';
import { SHTH_CHECKSTATE, closeCurrent } from '../../Acommon';
import { SourceUpdateAPI } from '../common/type';
import { IUpdateEnum } from '../common/UpdateReducer';
import { useSourceStep } from '../common/useSourceStep';
import { SourceUpdateContext } from '../common/UpdateContext';
import { AllBtnsConfig, useWorkFlowConfig } from '../mconfig';

import { getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { CheckCircleOutlined } from '@ant-design/icons';
import { updatePlanStateServices } from '../../ApplyManage/services/UpdateService';
import { syncApplyPackSerivice, syncPDFtoOAServices } from '../services/UpdateService';
import { syncApplyStateService } from '../../DocumentationManage/services/UpdateService';
import { WorkflowChedkRecord, WorkflowHndTaskBtn, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';

const SourceUpdateView: React.FC<SourceUpdateAPI.IUpdateView> = ({}) => {
  /** 上下文 */
  const {
    curRes,
    prefixCls,
    dispatch,
    locationProps,
    Source_Invite, //招标公告详情
    Source_Clarify, //澄清详情
    Source_PurchaseChange, //变更方式详情
    Source_Calibrate, // 定标详情
  } = useContext(SourceUpdateContext);
  const { info = {}, type } = locationProps?.state || {};

  /** 修改计划状态,采购申请审批同意后-修改计划状态信息 执行中 */
  const { updatePlanStateRun, updatePlanStateLoading } = updatePlanStateServices((res) => {
    if (res?.msgFlag) {
      message.success(res.msg);
      history.push({
        pathname: '/sourceController/manage',
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    } else {
      message.error(res?.msg);
    }
  });

  /**同步申请【采购中】接口*/
  const { syncApplyStateRun, syncApplyStateLoading } = syncApplyStateService((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      // 同步修改计划状态
      const params = {
        calibrateID: Source_Calibrate?.id,
        applyID: null,
        state: `2`,
      };
      updatePlanStateRun(params);
    } else {
      message.error(res?.msg);
    }
  });

  // 线下会议-定标-直接调接口
  const { syncApplyPackRun, syncApplyPackLoading } = syncApplyPackSerivice((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);

      // 同步修改申请状态
      syncApplyStateRun({
        calibrateID: Source_Calibrate?.id,
        state: `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1006`,
      });

      syncPDFtoOARun({ ...Source_Calibrate, paramObject: null });
    } else {
      message.error(res?.msg);
    }
  });

  /** 审批记录渲染控制 */
  const [isShowAuditRecord, setIsShowAuditRecord] = useState<boolean>(false);
  /** 是否打开切换流程组件 */
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  /** 定标线下的提交弹窗 */
  const [isShowSubmitModal, setIsShowSubmitModal] = useState<Record<string, any>>({
    isShow: false,
    resObj: null,
  });
  /** 点击按钮保存数据和弹框控制 */
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({ ...workFlowInfoObj, showWorkFlowModal: true });
    } else {
      setShowSwitchFlow(false);
    }
  };

  const { UpdateSourceInvite, SourceInviteFooter, fetchFindSourceInvite } = UpdateSourceInviteView(); //招标公告
  const { UpdateSourceClarify, SourceClarifyFooter, reloadClarifyDetail } = UpdateSourceClarifyView(); //招标文件澄清修改
  const { UpdateSourceExperts, SourceExpertsFooter, reloadExpertsDetail } = UpdateSourceExpertsView(); //组建评标委员会
  const { UpdateSourceSupplier, SourceSupplierFooter } = UpdateSourceSupplierView(); //开评标 [{ changeNoShowKeys }]
  const { UpdateSourceCalibrate, SourceCalibrateFooter, reloadCalibrateDetail } = UpdateSourceCalibrateView(); //定标

  /** 监听实施管理页面按钮  跳转相对应的步骤条页面 */
  useEffect(() => {
    if (type == 'clarify') {
      changeStep('custom', 1);
    } else if (type == 'supplier') {
      changeStep('custom', 3);
    } else if (type == 'calibrate') {
      changeStep('custom', 4);
    } else {
      changeStep('custom', 0);
    }
  }, [type]);

  /** 内容 */
  const container: Record<string, any> = {
    'source-tender': {
      title: '招标公告',
      content: UpdateSourceInvite,
      footer: SourceInviteFooter,
    },
    'source-clarify': {
      title: '招标文件澄清修改',
      content: UpdateSourceClarify,
      footer: SourceClarifyFooter,
    },
    'source-experts': {
      title: '组建评标委员会',
      content: UpdateSourceExperts,
      footer: SourceExpertsFooter,
    },
    'source-supplier': {
      title: '开评标',
      content: UpdateSourceSupplier,
      footer: SourceSupplierFooter,
    },
    'source-calibrate': {
      title: '定标',
      content: UpdateSourceCalibrate,
      footer: SourceCalibrateFooter,
    },
  };

  /** 步骤条配置 */
  const { currentStep, changeStep, stepsItems, setNoShowKeys } = useSourceStep({ info, container });

  /**监听步骤条*/
  useEffect(() => {
    dispatch({ type: IUpdateEnum?.Set_Source_CurrentStep, payload: currentStep });
  }, [currentStep]);

  /** 刷新详情 */
  const reloadDetailInfo = () => {
    if (stepsItems[currentStep]?.key == 'source-tender') {
      fetchFindSourceInvite(Source_Invite);
    } else if (stepsItems[currentStep]?.key == 'source-clarify') {
      reloadClarifyDetail(Source_Clarify);
    } else if (stepsItems[currentStep]?.key == 'source-experts') {
      reloadExpertsDetail();
    } else if (stepsItems[currentStep]?.key == 'source-change') {
      // reloadPageCallback();
    } else if (stepsItems[currentStep]?.key == 'source-calibrate') {
      reloadCalibrateDetail(Source_Calibrate);
    }
  };

  /** 处理返回数据详情 */
  const returnSwitchTypeInfo = () => {
    switch (stepsItems[currentStep]?.key) {
      case 'source-tender':
        return Source_Invite;
      case 'source-clarify':
        return Source_Clarify;
      case 'source-change':
        return Source_PurchaseChange;
      case 'source-calibrate':
        return Source_Calibrate;
      default:
        return { id: true };
    }
  };

  /** 实施工作流配置 */
  const workFlowConfig: any = useWorkFlowConfig({
    currentKey: stepsItems[currentStep]?.key,
    dataInfo: returnSwitchTypeInfo(),
  });

  /** 按钮是否显示 */
  const allBtnsMemo = useMemo(() => {
    const dataInfo: Record<string, any> = returnSwitchTypeInfo();
    const allBtns = AllBtnsConfig(curRes, dataInfo, workFlowConfig?.sourceCategory, stepsItems[currentStep]?.key);
    return allBtns;
  }, [curRes, currentStep, stepsItems, returnSwitchTypeInfo(), workFlowConfig?.sourceCategory]);

  const isAloneSubmitFn = (detailInfo: Record<string, any>, typeKey: string) => {
    switch (typeKey) {
      case 'source-calibrate':
        return detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1000` && detailInfo?.checkState == SHTH_CHECKSTATE();
    }
    return false;
  };

  /** 定标推送档案 */
  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServices(() => {});

  return (
    <div className={`${prefixCls}`}>
      <div className={`${prefixCls}container`}>
        <div className={`${prefixCls}container-steps`}>
          <Steps
            current={currentStep}
            items={stepsItems}
            size="small"
            onChange={(step) => {
              changeStep('custom', step);
            }}
          />
        </div>
        <div className={`${prefixCls}container-scroll`}>{stepsItems?.length > 0 && container[stepsItems[currentStep]?.key]?.content()}</div>
        <div className={`${prefixCls}container-footer`}>
          <Space>
            {container[stepsItems[currentStep]?.key]?.footer()}
            {/* 澄清 定标 流程提交 */}
            {allBtnsMemo?.applyBtnDiv && (
              <Button
                type={'primary'}
                onClick={() => {
                  // 定标提交 && 线下会议  不用走流程，直接改变状态
                  if (currentStep == 4 && Source_Calibrate?.calibrationMethod == 1) {
                    // 打开确认弹窗
                    setIsShowSubmitModal({
                      isShow: true,
                      resObj: {},
                    });
                  } else {
                    setWorkFlowInfoObj({
                      showWorkFlowModal: true,
                      saveNoDefaultFlowID: '',
                    });
                  }
                }}
              >
                提交
              </Button>
            )}
            {locationProps?.state?.returnPathName && (
              <Button danger onClick={() => closeCurrent(locationProps?.state?.returnPathName)}>
                关闭
              </Button>
            )}
            {/* 流程节点弹框 */}
            <WorkflowHndTaskBtn
              flowDetailInfo={allBtnsMemo?.flowHandList}
              reloadCallback={reloadDetailInfo}
              requestController={workFlowConfig?.sourceController}
              isAloneSubmit={isAloneSubmitFn(returnSwitchTypeInfo(), stepsItems[currentStep]?.key)}
              flowBusinessType={workFlowConfig?.sourceCategory}
              applyHeader={workFlowConfig?.applyHeader}
              revokeRequestUrl={workFlowConfig?.revokeRequestUrl}
              revokeRequestState={workFlowConfig?.revokeRequestState}
              isShowRevokeStateList={workFlowConfig?.isShowRevokeStateList}
              revokeTitle={workFlowConfig?.revokeTitle}
              revokeSuccessCallback={reloadDetailInfo}
            />
          </Space>
        </div>

        {/* 审核记录 */}
        {workFlowConfig?.sourceDetailInfo?.id &&
          // stepsItems[currentStep]?.key == 'source-tender' ||
          (stepsItems[currentStep]?.key == 'source-clarify' ||
            // stepsItems[currentStep]?.key == 'source-change' ||
            stepsItems[currentStep]?.key == 'source-calibrate') &&
          workFlowConfig?.sourceDetailInfo?.paramObject?.[workFlowConfig?.sourceCategory] && (
            <WorkflowChedkRecord
              curRes={curRes}
              dataDetailInfo={workFlowConfig?.sourceDetailInfo}
              flowBusinessType={workFlowConfig?.sourceCategory}
              requestController={workFlowConfig?.sourceController}
              reloadPageCallback={reloadDetailInfo}
              revokeStateID={workFlowConfig?.source?.revokeStateID}
              allBtnFuncQuqry={allBtnsMemo}
              tabPaneHeight={0.35}
              isCheckDrawer={true}
              isShowCollapse={isShowAuditRecord}
              changeCollapse={(val) => setIsShowAuditRecord(val)}
              cancelStateId={workFlowConfig?.sourceCancelState}
              isSyncArchive={true}
            />
          )}

        {/* 发起流程审批 */}
        {workFlowInfoObj?.showWorkFlowModal && (
          <WorkflowSwitchModal
            openVisible={workFlowInfoObj?.showWorkFlowModal}
            onClose={() => {
              setWorkFlowInfoObj({
                ...workFlowInfoObj,
                showWorkFlowModal: false,
              });
            }}
            businessInfoObj={workFlowConfig?.sourceDetailInfo}
            requestController={workFlowConfig?.sourceController}
            orderType={workFlowConfig?.sourceOrderType}
            category={workFlowConfig?.sourceCategory}
            businessCategory={workFlowConfig?.sourceBusinessCategory}
            reloadInfoCallback={reloadDetailInfo}
            openFlowChangeModal={setShowSwitchFlow}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
            replaceStrObj={workFlowConfig?.sourceApplyFields}
            startWorkFlowCallback={() => {
              history.push({
                pathname: '/sourceController/manage',
                state: {
                  delRouterNameSource: history.location.pathname,
                },
              });
            }}
          />
        )}

        {/* 挑选流程组件 */}
        {showSwitchFlow && (
          <WorkflowNoDefaultTable
            openVisibleSwitch={showSwitchFlow}
            onCloseSwitch={closeSwitchFlowModal}
            requestController={workFlowConfig?.sourceController}
            orderType={workFlowConfig?.sourceOrderType}
            category={workFlowConfig?.sourceCategory}
            businessCategory={workFlowConfig?.sourceBusinessCategory}
            saveSelectFlowID={(flowId: string) => {
              setWorkFlowInfoObj({
                ...workFlowInfoObj,
                saveNoDefaultFlowID: flowId,
              });
            }}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
          />
        )}

        {/* 公告的提交弹窗 */}
        {isShowSubmitModal?.isShow && (
          <TipsErrorModalNew
            bodyWidth={0.25}
            onClose={() => setIsShowSubmitModal({ isShow: false, resObj: null })}
            modalOnOK={() => {
              syncApplyPackRun({
                id: Source_Calibrate?.id,
                state: `${getTenantID()}${ILoadMapTypeAll?.CALIBRATE_STATE}1002`,
                sourceState: `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1014`,
              });
            }}
            modalLoading={syncApplyPackLoading}
            modalTip={'请确认此次定标申请信息无误，提交后不可修改!'}
          />
        )}
      </div>
    </div>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(SourceUpdateView);
